package com.csx.base.design.behavior.mediator;

import lombok.Data;

import java.util.Objects;

/**
 * @author cuisongxu
 * @date 2022/10/10 11:55
 */
@Data
public class User {

    private String name;

    private ChatRoom chatRoom;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    /**
     * 用户登录
     * @param chatRoom
     */
    public void login(ChatRoom chatRoom) {
        this.chatRoom = chatRoom;
        this.chatRoom.register(this);
    }

    public void logout() {
        chatRoom.deregister(this);
        this.chatRoom = null;
    }

    public void talk(User to, String msg) {
        if(Objects.isNull(chatRoom)) {
            System.out.println("【" + name + "的对话框】" + "您还没有登录");
            return;
        }
        // 给聊天室发送消息
        chatRoom.sendMsg(this, to, msg);
    }

    public void listen(User from, User to, String msg) {
        System.out.print("【" + this.getName() + "的对话框】");
        System.out.println(chatRoom.processMsg(from, to, msg));

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        User user = (User) o;
        return Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}
